package cn.virens.common.project.base.utils;

import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.io.file.FileNameUtil;
import org.dromara.hutool.core.io.file.FileUtil;
import org.dromara.hutool.core.net.url.UrlUtil;
import org.dromara.hutool.http.client.HttpDownloader;

import java.io.File;
import java.io.InputStream;

public class CertificateUtil {

    public static InputStream getInputStream(String name, String url) throws APIException {
        return FileUtil.getInputStream(getCertFile(name, url));
    }

    public static InputStream getCertificateWeipay(String url) throws APIException {
        return getInputStream("weipay.tmp", url);
    }

    public static InputStream getCertificateAlipay(String url) throws APIException {
        return getInputStream("alipay.tmp", url);
    }

    public static File getCertFile(String name, String url) throws APIException {
        return getFile(FileNameUtil.normalize(".cert/" + name), url);
    }

    public static File getFile(String path, String url) throws APIException {
        File file0 = FileUtil.file(UrlUtil.CLASSPATH_URL_PREFIX + path);
        if ((null != file0) && file0.exists()) {
            return file0;
        }

        String userDir = System.getProperty("user.dir");
        File file1 = FileUtil.file(userDir, path);
        if ((null != file1) && file1.exists()) {
            return file1;
        }

        // 从网络中下载对应的证书文件存储到本地---------------------
        return HttpDownloader.of(url).downloadFile(file1);//
    }
}
